<?php

namespace app\common\model\server;

use app\common\model\BaseModel;

/**
 * 服务人员用户模型
 * Class Apply
 * @package app\common\model\dealer
 */
class User extends BaseModel
{
    protected $name = 'server_user';

    /**
     * 关联会员记录表
     * @return \think\model\relation\BelongsTo
     */
    public function user()
    {
        return $this->belongsTo('app\common\model\User');
    }

    /**
     * 获取服务人员用户信息
     * @param $userId
     * @param array $with
     * @return static|null
     * @throws \think\exception\DbException
     */
    public static function detail($userId, $with = ['user'])
    {
        return self::get($userId, $with);
    }

    /**
     * 是否为服务人员
     * @param $userId
     * @return bool
     */
    public static function isDealerUser($userId)
    {
        return !!(new static)->where('user_id', '=', $userId)
            ->where('is_delete', '=', 0)
            ->value('user_id');
    }

    /**
     * 新增服务人员记录
     * @param $user_id
     * @param $data
     * @return false|int
     * @throws \think\exception\DbException
     */
    public static function add($user_id, $data)
    {
        $model = static::detail($user_id) ?: new static;
        return $model->save(array_merge([
            'user_id' => $user_id,
            'is_delete' => 0,
            'wxapp_id' => $model::$wxapp_id
        ], $data));
    }

    /**
     * 发放服务人员工资
     * @param $user_id
     * @param $money
     * @return bool
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public static function grantMoney($user_id, $money, $remark = '')
    {
        // 服务人员详情
        $model = static::detail($user_id);
        if (!$model || $model['is_delete']) {
            return false;
        }
        // 累积服务人员可提现佣金
        $model->setInc('money', $money);
        // 记录服务人员资金明细
        Capital::add([
            'user_id' => $user_id,
            'flow_type' => 10,
            'money' => $money,
            'current_money' => $model['money'],
            'describe' => $remark ? $remark : '订单服务结算',
            'wxapp_id' => $model['wxapp_id'],
        ]);
        return true;
    }

    /*
     * 我的银行卡信息
     */
    public static function bankInfo($user_id)
    {
        $model = static::detail($user_id);
        if (!$model || $model['is_delete']) {
            return false;
        }

        $data = [
            'bank_name' => $model['bank_name'],
            'bank_account' => $model['bank_account'],
            'bank_card' => $model['bank_card']
        ];

        return $data;
    }

    /*
     * 当前可预约服务人员
     */
    public static function allServer($type, $ids = [])
    {
        $list = static::where(['is_delete' => 0, 'wxapp_id' => self::$wxapp_id/*, 'user_id' => ['not in', $ids]*/])
            ->where('find_in_set(:type_ids,type_ids)', ['type_ids' => $type])
            ->field('real_name,user_id')->select()->toArray();
        return $list;

    }

}